package auth

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/kataras/iris/v12"
	"github.com/spf13/viper"
	"strconv"
	"time"
)

type UserAuthorization struct {
	Uid      string    `json:"uid"`
	Username string    `json:"username"`
	Time     time.Time `json:"time"`
	jwt.StandardClaims
}

// User 获取当前用户信息
func User(ctx iris.Context) (*UserAuthorization, error) {
	token, err := jwt.ParseWithClaims(ctx.GetHeader("Authorization")[7:], &UserAuthorization{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(viper.GetString("app.key")), nil
	})

	if claims, ok := token.Claims.(*UserAuthorization); ok && token.Valid {
		return claims, nil
	} else {
		return claims, err
	}
}

// Check 检查用户是否登录
func Check(ctx iris.Context) bool {
	_, err := User(ctx)
	if err != nil {
		return false
	}

	return true
}

// Uid 获取当前登录用户的ID
func Uid(ctx iris.Context) int {
	claims, err := User(ctx)
	if err != nil {
		return 0
	}

	uid, _ := strconv.Atoi(claims.Uid)

	return uid
}
